﻿using AutoMapper;
using MD5Hash;
using MediatR;
using SmartTracking.API.Write.Application.Commands.User_command;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Write.Application.CommandHandlers.User_handler
{
    public class UpdateUserCommandHandler:IRequestHandler<UpdateUserCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<UserRoleMiddle> urRep;
        private readonly IMapper mapper;

        public UpdateUserCommandHandler(
            IBaseRepository<Users> userRep,
            IBaseRepository<UserRoleMiddle> urRep,
            IMapper mapper)
        {
            this.userRep = userRep;
            this.urRep = urRep;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.更新成功;
            result.Message = ApiEnum.更新成功.ToString();

            using (var tran = userRep.DB.Database.BeginTransaction())
            {
                try
                {
                    #region 更新用户信息
                    Users users = mapper.Map<Users>(request);
                    users.Password = request.Password.GetMD5();
                    users.UpdateTime = DateTime.Now;
                    var list = await userRep.UpdateAsync(users);
                    #endregion

                    #region 修改用户角色中间表
                    List<UserRoleMiddle> userRoles = new List<UserRoleMiddle>();
                    var urlist = urRep.GetAll().Where(x => x.UserId == request.UserId).ToList();
                    foreach (var item in urlist)
                    {
                        urlist.Remove(new UserRoleMiddle()
                        {
                            UserId = users.UserId,
                            RoleId = item.RoleId,
                        });
                    }
                    await urRep.DeleteRangeAsync(urlist);

                    foreach (var item in request.RoleId)
                    {
                        userRoles.Add(new UserRoleMiddle()
                        {
                            UserId = users.UserId,
                            RoleId = item,
                        });
                    }
                    await urRep.AddRangeAsync(userRoles);
                    #endregion

                    tran.Commit();
                    result.data = list;
                }
                catch (Exception ex) 
                {
                    result.Code = ApiEnum.更新失败;
                    result.Message = ApiEnum.更新失败.ToString()+","+ ex.Message;
                    tran.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
